# -*- coding: utf-8 -*-
import base64
import json
import logging
from urllib.parse import unquote_plus
import werkzeug.urls
import werkzeug.utils
from werkzeug.exceptions import BadRequest

from odoo import http
from odoo.exceptions import AccessDenied
from odoo.http import request
from odoo.addons.web.controllers.utils import ensure_db, _get_login_redirect_url

_logger = logging.getLogger(__name__)


class WecomOAuthController(http.Controller):
    @http.route("/wecom_oauth/authorize", type="http", auth="none")
    def wecom_oauth_authorize(self, **kw):
        state = json.loads(base64.standard_b64decode(kw['state']))
        dbname = state['db']
        if not http.db_filter([dbname]):
            return BadRequest()
        url = unquote_plus(state['redirect']) if state.get('redirect') else '/web'
        wecom_app = request.env["wecom.app"].browse(state['wecom_app_id'])
        user_info = wecom_app.get_user_info(kw['code'])
        _logger.info('user_info from wecom:%s', user_info)
        userid = user_info['UserId']
        try:
            pre_uid = request.session.authenticate(dbname, userid, "wecom->" + userid)
            resp = request.redirect(_get_login_redirect_url(pre_uid, url), 303)
            resp.autocorrect_location_header = False

            # Since /web is hardcoded, verify user has right to land on it
            if werkzeug.urls.url_parse(resp.location).path == '/web' and not request.env.user._is_internal():
                resp.location = '/'
            return resp
        except AccessDenied:
            # oauth credentials not valid, user could be on a temporary session
            _logger.info(
                'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
            url = "/web/login?oauth_error=3"
        except Exception as e:
            # signup error
            _logger.exception("wecom_oauth_authorize : %s" % str(e))
            url = "/web/login?oauth_error=2"
        redirect = request.redirect(url, 303)
        redirect.autocorrect_location_header = False
        return redirect
